<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二手易购 - 商品首页</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 全局样式 */
        :root {
            --primary: #1a1a1a;
            --secondary: #333333;
            --accent: #666666;
            --light: #f5f5f5;
            --white: #ffffff;
            --dark: #000000;
            --light-gray: #e0e0e0;
            --medium-gray: #999999;
            --success: #28a745;
            --error: #dc3545;
            --warning: #ffc107;
            --shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            --transition: all 0.2s ease; /* 减少过渡时间 */
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        body {
            background: linear-gradient(135deg, #f8f9fa 0%, #eef0f2 100%);
            color: var(--dark);
            min-height: 100vh;
            padding-bottom: 80px;
        }

        /* 顶部导航栏 */
        .navbar {
            background: var(--white);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            padding: 12px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .logo {
            display: flex;
            align-items: center;
            transform-origin: left center;
        }

        .logo:hover {
            transform: scale(1.03);
        }

        .logo h1 {
            font-size: 22px;
            font-weight: 700;
            color: var(--dark);
            margin-left: 8px;
            letter-spacing: -0.5px;
        }

        .logo i {
            font-size: 24px;
            color: var(--accent);
        }

        .search-container {
            flex: 1;
            max-width: 550px;
            margin: 0 15px;
            position: relative;
        }

        .search-container input {
            width: 100%;
            padding: 12px 20px;
            border: 1px solid var(--light-gray);
            border-radius: 25px;
            font-size: 14px;
            transition: var(--transition);
            background-color: var(--white);
            color: var(--dark);
            outline: none;
            padding-right: 45px;
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.05);
        }

        .search-container input:focus {
            box-shadow: 0 3px 12px rgba(0, 0, 0, 0.1);
            border-color: var(--accent);
        }

        .search-container button {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--accent);
            cursor: pointer;
            font-size: 16px;
        }

        .nav-links {
            display: flex;
            gap: 20px;
        }

        .nav-link {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: var(--dark);
            font-size: 13px;
            transition: var(--transition);
            position: relative;
            padding: 4px 8px;
            border-radius: 6px;
        }

        .nav-link i {
            font-size: 18px;
            margin-bottom: 3px;
        }

        .nav-link:hover {
            color: var(--accent);
            background-color: rgba(0, 0, 0, 0.03);
        }

        .nav-link .badge {
            position: absolute;
            top: -4px;
            right: -4px;
            background-color: var(--error);
            color: var(--white);
            border-radius: 50%;
            width: 18px;
            height: 18px;
            font-size: 11px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.15);
        }

        .user-menu {
            display: flex;
            align-items: center;
            cursor: pointer;
            position: relative;
        }

        .user-avatar {
            width: 38px;
            height: 38px;
            border-radius: 50%;
            background: linear-gradient(135deg, #e0e0e0, #f0f0f0);
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            margin-left: 12px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        .user-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .user-avatar i {
            font-size: 18px;
            color: var(--accent);
        }

        .dropdown-menu {
            position: absolute;
            top: 50px;
            right: 0;
            background: var(--white);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
            border-radius: 10px;
            width: 180px;
            overflow: hidden;
            display: none;
            z-index: 1000;
        }

        .dropdown-menu.show {
            display: block;
        }

        .dropdown-item {
            padding: 10px 16px;
            display: flex;
            align-items: center;
            text-decoration: none;
            color: var(--dark);
            transition: var(--transition);
            position: relative;
            font-size: 14px;
        }

        .dropdown-item:hover {
            background-color: rgba(0, 0, 0, 0.05);
            padding-left: 20px;
        }

        .dropdown-item:hover::before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 3px;
            background: var(--dark);
        }

        .dropdown-item i {
            margin-right: 8px;
            width: 18px;
            text-align: center;
            font-size: 14px;
        }

        .divider {
            height: 1px;
            background-color: var(--light-gray);
            margin: 4px 0;
        }

        /* 内容区域 */
        .container {
            max-width: 1300px;
            margin: 25px auto;
            padding: 0 20px;
        }

        /* 分类筛选 */
        .categories-section {
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--light-gray);
        }

        .categories-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
            color: var(--secondary);
            position: relative;
            display: inline-block;
            padding-bottom: 6px;
        }

        .categories-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 45px;
            height: 3px;
            background: var(--dark);
            border-radius: 2px;
        }

        .categories {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .category-btn {
            padding: 8px 20px;
            background-color: var(--white);
            border: 1px solid var(--light-gray);
            border-radius: 25px;
            cursor: pointer;
            transition: var(--transition);
            font-size: 13px;
            font-weight: 500;
            position: relative;
            overflow: hidden;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        }

        .category-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 0;
            height: 100%;
            background: var(--dark);
            transition: width 0.3s ease;
            z-index: -1;
        }

        .category-btn:hover, .category-btn.active {
            color: var(--white);
            border-color: var(--dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .category-btn:hover::before, .category-btn.active::before {
            width: 100%;
        }

        /* 商品网格 */
        .products-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 25px;
            margin-bottom: 35px;
        }

        .product-card {
            background: var(--white);
            border-radius: 14px;
            overflow: hidden;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
            transition: var(--transition);
            cursor: pointer;
            position: relative;
            transform: translateY(0);
            opacity: 1;
        }

        .product-card:hover {
            transform: translateY(-6px);
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
        }

        .product-image {
            width: 100%;
            height: 180px;
            background: linear-gradient(135deg, #f0f0f0, #e0e0e0);
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            position: relative;
        }

        .product-image::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 35%;
            background: linear-gradient(to top, rgba(0,0,0,0.1), transparent);
        }

        .product-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.4s ease;
        }

        .product-card:hover .product-image img {
            transform: scale(1.08);
        }

        .product-info {
            padding: 15px;
        }

        .product-name {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            height: 44px;
            transition: color 0.2s ease;
        }

        .product-card:hover .product-name {
            color: var(--accent);
        }

        .product-description {
            font-size: 12px;
            color: var(--medium-gray);
            margin-bottom: 10px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            height: 34px;
            line-height: 1.5;
        }

        .product-price {
            font-size: 17px;
            font-weight: 700;
            color: var(--dark);
            letter-spacing: -0.5px;
        }

        .product-meta {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
            font-size: 11px;
            color: var(--medium-gray);
        }

        .product-meta span:first-child {
            background: rgba(0,0,0,0.05);
            padding: 2px 6px;
            border-radius: 10px;
        }

        .product-tag {
            position: absolute;
            top: 12px;
            left: 12px;
            background: var(--dark);
            color: white;
            padding: 4px 10px;
            border-radius: 18px;
            font-size: 11px;
            font-weight: 600;
            z-index: 2;
            box-shadow: 0 2px 6px rgba(0,0,0,0.15);
        }

        /* 模态框 - 商品详情 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 2000;
            overflow-y: auto;
            padding: 15px;
        }

        .modal-content {
            background: var(--white);
            border-radius: 16px;
            max-width: 800px;
            margin: 30px auto;
            position: relative;
            box-shadow: 0 20px 45px rgba(0,0,0,0.2);
        }

        .modal-header {
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--light-gray);
        }

        .modal-title {
            font-size: 20px;
            font-weight: 700;
            letter-spacing: -0.5px;
        }

        .close-modal {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--medium-gray);
            transition: var(--transition);
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .close-modal:hover {
            color: var(--dark);
            background: rgba(0,0,0,0.05);
        }

        .modal-body {
            padding: 20px;
            display: flex;
            flex-wrap: wrap;
        }

        .product-gallery {
            flex: 1;
            min-width: 280px;
            margin-right: 25px;
        }

        .main-image {
            width: 100%;
            height: 360px;
            background: linear-gradient(135deg, #f0f0f0, #e0e0e0);
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 15px;
            position: relative;
            box-shadow: 0 8px 18px rgba(0,0,0,0.08);
        }

        .main-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.4s ease;
        }

        .main-image:hover img {
            transform: scale(1.03);
        }

        .thumbnails {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .thumbnail {
            width: 70px;
            height: 70px;
            background: linear-gradient(135deg, #f0f0f0, #e0e0e0);
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        .thumbnail:hover {
            transform: translateY(-4px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.15);
        }

        .thumbnail img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .product-details {
            flex: 1;
            min-width: 280px;
        }

        .product-title {
            font-size: 24px;
            font-weight: 800;
            margin-bottom: 15px;
            letter-spacing: -0.5px;
            line-height: 1.2;
        }

        .product-meta-info {
            display: flex;
            margin-bottom: 20px;
            gap: 15px;
            font-size: 14px;
            color: var(--medium-gray);
        }

        .price-section {
            background: linear-gradient(135deg, #f8f9fa, #f0f2f4);
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid rgba(0,0,0,0.05);
        }

        .price-label {
            font-size: 14px;
            color: var(--medium-gray);
            margin-bottom: 4px;
            font-weight: 500;
        }

        .price-value {
            font-size: 32px;
            font-weight: 800;
            color: var(--dark);
            margin-bottom: 20px;
            letter-spacing: -1px;
        }

        .stock-info {
            font-size: 14px;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
        }

        .stock-info span {
            color: var(--success);
            font-weight: 600;
            margin-left: 6px;
            font-size: 15px;
        }

        .quantity-control {
            display: flex;
            align-items: center;
            margin: 20px 0;
        }

        .quantity-label {
            margin-right: 12px;
            font-weight: 600;
            font-size: 15px;
        }

        .quantity-btn {
            width: 36px;
            height: 36px;
            background: var(--light-gray);
            border: none;
            border-radius: 8px;
            font-size: 18px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        .quantity-btn:hover {
            background: var(--accent);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0,0,0,0.15);
        }

        .quantity-btn:disabled {
            background-color: #f0f0f0;
            color: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .quantity-input {
            width: 55px;
            height: 36px;
            text-align: center;
            border: 1px solid var(--light-gray);
            border-radius: 8px;
            margin: 0 10px;
            font-size: 16px;
            font-weight: 600;
            box-shadow: inset 0 1px 4px rgba(0,0,0,0.05);
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 25px;
        }

        .btn {
            padding: 14px 25px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            border: none;
            position: relative;
            overflow: hidden;
            letter-spacing: 0.5px;
        }

        .btn i {
            margin-right: 8px;
        }

        .btn-dark {
            background: var(--dark);
            color: var(--white);
            flex: 1;
            box-shadow: 0 6px 18px rgba(0,0,0,0.2);
        }

        .btn-dark:hover {
            background: #111;
            transform: translateY(-3px);
            box-shadow: 0 10px 22px rgba(0,0,0,0.25);
        }

        .btn-outline {
            background: transparent;
            border: 2px solid var(--dark);
            color: var(--dark);
            flex: 1;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        .btn-outline:hover {
            background-color: var(--dark);
            color: var(--white);
            transform: translateY(-3px);
            box-shadow: 0 8px 18px rgba(0,0,0,0.15);
        }

        .product-description-full {
            margin: 30px 0;
            line-height: 1.7;
            font-size: 15px;
            color: #444;
            border-left: 3px solid var(--dark);
            padding-left: 15px;
        }

        .tabs {
            display: flex;
            border-bottom: 1px solid var(--light-gray);
            margin: 25px 0 18px;
        }

        .tab {
            padding: 12px 25px;
            cursor: pointer;
            font-weight: 600;
            transition: var(--transition);
            border-bottom: 3px solid transparent;
            position: relative;
            font-size: 15px;
        }

        .tab:hover {
            color: var(--accent);
        }

        .tab.active {
            border-bottom: 3px solid var(--dark);
            color: var(--dark);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .comments-section {
            margin-top: 25px;
        }

        .comment {
            padding: 20px;
            border-bottom: 1px solid var(--light-gray);
        }

        .comment-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        .comment-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #e0e0e0, #f0f0f0);
            margin-right: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        .comment-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .comment-user {
            font-weight: 700;
            font-size: 15px;
        }

        .comment-text {
            line-height: 1.6;
            text-align: left;
            font-size: 14px;
            padding-left: 52px;
        }

        .no-comments {
            text-align: center;
            padding: 30px;
            color: var(--medium-gray);
        }

        .no-comments i {
            font-size: 45px;
            opacity: 0.3;
            margin-bottom: 12px;
        }

        .comments-title {
            text-align: center;
            font-size: 22px;
            font-weight: 700;
            margin: 25px 0;
            color: var(--dark);
            position: relative;
            padding-bottom: 12px;
        }

        .comments-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 70px;
            height: 3px;
            background: var(--dark);
            border-radius: 2px;
        }

        /* 库存提示 */
        .stock-warning {
            color: var(--error);
            font-size: 13px;
            margin-top: 6px;
            height: 18px;
            opacity: 0;
            transition: opacity 0.2s ease;
            font-weight: 500;
            padding-left: 8px;
        }

        .stock-warning.show {
            opacity: 1;
        }

        /* 响应式设计 */
        @media (max-width: 992px) {
            .navbar {
                flex-wrap: wrap;
                padding: 12px 15px;
            }

            .logo h1 {
                font-size: 18px;
            }

            .search-container {
                order: 3;
                max-width: 100%;
                margin: 12px 0 0;
            }

            .nav-links {
                gap: 12px;
            }

            .product-gallery,
            .product-details {
                min-width: 100%;
                margin-right: 0;
                margin-bottom: 25px;
            }
        }

        @media (max-width: 768px) {
            .nav-links {
                display: none;
            }

            .products-grid {
                grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
                gap: 18px;
            }

            .product-image {
                height: 150px;
            }

            .main-image {
                height: 280px;
            }
        }

        /* 加载动画 */
        .loader {
            display: none;
            text-align: center;
            padding: 50px 0;
        }

        .loader .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: var(--dark);
            animation: spin 1.2s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 70px 20px;
            color: var(--medium-gray);
        }

        .empty-state i {
            font-size: 60px;
            margin-bottom: 20px;
            opacity: 0.2;
        }

        .empty-state h3 {
            font-size: 24px;
            margin-bottom: 15px;
            color: var(--secondary);
            font-weight: 700;
        }

        .empty-state p {
            font-size: 16px;
            max-width: 450px;
            margin: 0 auto;
            line-height: 1.6;
        }

        /* 浮动发布按钮 */
        .floating-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 65px;
            height: 65px;
            background: var(--dark);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 25px;
            box-shadow: 0 5px 22px rgba(0, 0, 0, 0.25);
            cursor: pointer;
            z-index: 100;
            transition: all 0.3s ease;
        }

        .floating-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 8px 28px rgba(0, 0, 0, 0.3);
        }

        .floating-btn::after {
            content: "发布商品";
            position: absolute;
            top: -38px;
            left: 50%;
            transform: translateX(-50%);
            background: var(--dark);
            color: white;
            padding: 5px 12px;
            border-radius: 5px;
            font-size: 13px;
            white-space: nowrap;
            opacity: 0;
            transition: opacity 0.3s;
            font-weight: 500;
        }

        .floating-btn:hover::after {
            opacity: 1;
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 10px;
            background-color: var(--success);
            color: white;
            font-weight: 600;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            z-index: 3000;
            font-size: 15px;
        }

        .notification.error {
            background-color: var(--error);
        }

        /* 页面标题 */
        .page-title {
            text-align: center;
            margin: 35px 0 45px;
            position: relative;
        }

        .page-title h2 {
            font-size: 32px;
            font-weight: 800;
            letter-spacing: -1px;
            margin-bottom: 12px;
        }

        .page-title p {
            font-size: 17px;
            color: var(--medium-gray);
            max-width: 550px;
            margin: 0 auto;
            line-height: 1.6;
        }

        .page-title::after {
            content: '';
            position: absolute;
            bottom: -18px;
            left: 50%;
            transform: translateX(-50%);
            width: 90px;
            height: 3px;
            background: var(--dark);
            border-radius: 2px;
        }

        /* 购物车提示选择框 */
        .cart-confirm-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 2500;
            display: none;
            justify-content: center;
            align-items: center;
        }

        .cart-confirm-content {
            background: var(--white);
            border-radius: 16px;
            width: 380px;
            padding: 35px 30px;
            text-align: center;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
            position: relative;
        }

        .cart-confirm-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: rgba(40, 167, 69, 0.15);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
        }

        .cart-confirm-icon i {
            font-size: 42px;
            color: var(--success);
        }

        .cart-confirm-title {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 15px;
            color: var(--dark);
        }

        .cart-confirm-text {
            font-size: 16px;
            color: var(--medium-gray);
            line-height: 1.6;
            margin-bottom: 30px;
        }

        .cart-confirm-buttons {
            display: flex;
            gap: 15px;
        }

        .cart-confirm-btn {
            flex: 1;
            padding: 14px 0;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            border: 2px solid transparent;
        }

        .cart-confirm-btn.continue {
            background: var(--white);
            border-color: var(--dark);
            color: var(--dark);
        }

        .cart-confirm-btn.continue:hover {
            background: var(--light-gray);
            transform: translateY(-2px);
        }

        .cart-confirm-btn.view-cart {
            background: var(--dark);
            color: var(--white);
        }

        .cart-confirm-btn.view-cart:hover {
            background: #111;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }

        /* 购物车失败提示框 */
        .cart-error-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 2500;
            display: none;
            justify-content: center;
            align-items: center;
        }

        .cart-error-content {
            background: var(--white);
            border-radius: 16px;
            width: 380px;
            padding: 35px 30px;
            text-align: center;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
            position: relative;
        }

        .cart-error-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: rgba(220, 53, 69, 0.15);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
        }

        .cart-error-icon i {
            font-size: 42px;
            color: var(--error);
        }

        .cart-error-title {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 15px;
            color: var(--dark);
        }

        .cart-error-text {
            font-size: 16px;
            color: var(--medium-gray);
            line-height: 1.6;
            margin-bottom: 30px;
        }

        .cart-error-button {
            display: block;
            width: 100%;
            padding: 14px 0;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            background: var(--dark);
            color: var(--white);
            border: none;
        }

        .cart-error-button:hover {
            background: #111;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }

        /* 商品发布模态框 */
        .publish-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 2000;
            overflow-y: auto;
            padding: 15px;
        }

        .publish-content {
            background: var(--white);
            border-radius: 16px;
            max-width: 600px;
            margin: 30px auto;
            position: relative;
            box-shadow: 0 20px 45px rgba(0,0,0,0.2);
        }

        .publish-header {
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--light-gray);
        }

        .publish-title {
            font-size: 20px;
            font-weight: 700;
            letter-spacing: -0.5px;
        }

        .close-publish {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--medium-gray);
            transition: var(--transition);
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .close-publish:hover {
            color: var(--dark);
            background: rgba(0,0,0,0.05);
        }

        .publish-body {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--dark);
            position: relative;
        }

        .form-label::after {
            content: "*";
            color: var(--error);
            margin-left: 4px;
        }

        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid var(--light-gray);
            border-radius: 10px;
            font-size: 15px;
            transition: var(--transition);
            background-color: var(--white);
            color: var(--dark);
            outline: none;
        }

        .form-control:focus {
            border-color: var(--dark);
            box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.05);
        }

        .form-control::placeholder {
            color: var(--medium-gray);
        }

        .form-hint {
            font-size: 13px;
            color: var(--medium-gray);
            margin-top: 5px;
            display: block;
        }

        .publish-action {
            display: flex;
            gap: 15px;
            margin-top: 25px;
        }

        .btn-cancel {
            background: var(--white);
            border: 2px solid var(--light-gray);
            color: var(--dark);
            flex: 1;
        }

        .btn-cancel:hover {
            background-color: #f5f5f5;
            transform: translateY(-3px);
        }

        .btn-publish {
            background: var(--dark);
            color: var(--white);
            flex: 1;
        }

        .btn-publish:hover {
            background: #111;
            transform: translateY(-3px);
            box-shadow: 0 8px 18px rgba(0,0,0,0.15);
        }

        .btn-publish:disabled {
            background-color: #999;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .btn-publish:disabled:hover {
            background-color: #999;
        }

        /* 表单错误提示 */
        .error-message {
            color: var(--error);
            font-size: 13px;
            margin-top: 5px;
            display: none;
        }

        /* 价格输入框样式 */
        .price-input-container {
            position: relative;
        }

        .price-prefix {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--dark);
            font-weight: 600;
        }

        .price-input {
            padding-left: 30px;
        }

        /* 分类选择样式 */
        .category-select {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid var(--light-gray);
            border-radius: 10px;
            font-size: 15px;
            background-color: var(--white);
            color: var(--dark);
            outline: none;
            transition: var(--transition);
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 1rem center;
            background-size: 1em;
        }

        .category-select:focus {
            border-color: var(--dark);
            box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.05);
        }

        /* 余额确认模态框样式 */
        .balance-confirm-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 2500;
            justify-content: center;
            align-items: center;
        }

        .balance-confirm-content {
            background: var(--white);
            border-radius: 16px;
            width: 400px;
            overflow: hidden;
            box-shadow: 0 20px 45px rgba(0,0,0,0.2);
        }

        .balance-confirm-header {
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--light-gray);
            background-color: var(--dark);
            color: var(--white);
        }

        .balance-confirm-header h3 {
            font-size: 18px;
            font-weight: 600;
            margin: 0;
        }

        .close-balance-modal {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--white);
        }

        .balance-confirm-body {
            padding: 25px;
        }

        .balance-info {
            margin-bottom: 20px;
        }

        .balance-info p {
            font-size: 16px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
        }

        .balance-info span {
            font-weight: 700;
            color: var(--dark);
        }

        .balance-action {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }

        .btn-cancel {
            padding: 10px 20px;
            background: var(--light-gray);
            color: var(--dark);
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-confirm {
            padding: 10px 20px;
            background: var(--dark);
            color: var(--white);
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-cancel:hover {
            background: #ddd;
        }

        .btn-confirm:hover {
            background: #111;
        }

        /* 订单确认模态框样式 */
        .order-confirm-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 3000;
            justify-content: center;
            align-items: center;
        }

        .order-confirm-content {
            background: var(--white);
            border-radius: 16px;
            width: 420px;
            padding: 35px 30px;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
            position: relative;
        }

        /* 订单错误提示模态框样式 */
        .order-error-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 3000;
            justify-content: center;
            align-items: center;
        }

        .order-error-content {
            background: var(--white);
            border-radius: 16px;
            width: 380px;
            padding: 35px 30px;
            text-align: center;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
            position: relative;
        }

        /* 订单成功确认模态框样式 - 美化 */
        .order-confirm-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 3000;
            justify-content: center;
            align-items: center;
        }

        .order-confirm-content {
            background: var(--white);
            border-radius: 16px;
            width: 420px;
            overflow: hidden;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
            position: relative;
        }

        .order-confirm-header {
            padding: 20px;
            background: var(--dark);
            color: var(--white);
            text-align: center;
            position: relative;
        }

        .order-confirm-title {
            font-size: 22px;
            font-weight: 700;
            margin: 0;
            letter-spacing: -0.5px;
        }

        .close-confirm {
            position: absolute;
            top: 15px;
            right: 15px;
            background: none;
            border: none;
            color: var(--white);
            font-size: 28px;
            cursor: pointer;
            opacity: 0.8;
            transition: var(--transition);
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .close-confirm:hover {
            opacity: 1;
            background: rgba(255, 255, 255, 0.15);
        }

        .order-details {
            padding: 30px;
            background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
            border-bottom: 1px solid var(--light-gray);
        }

        .order-detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px dashed var(--light-gray);
        }

        .order-detail-row:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }

        .order-detail-label {
            color: var(--medium-gray);
            font-size: 16px;
            font-weight: 500;
        }

        .order-detail-value {
            color: var(--dark);
            font-size: 16px;
            font-weight: 600;
            text-align: right;
        }

        .total-price {
            font-size: 20px !important;
            font-weight: 700 !important;
            color: var(--dark) !important;
        }

        .order-actions {
            padding: 25px;
            display: flex;
            gap: 15px;
        }

        .order-btn {
            flex: 1;
            padding: 14px 0;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }

        .order-btn i {
            margin-right: 8px;
            font-size: 18px;
        }

        .order-btn.continue {
            background: var(--white);
            border-color: var(--dark);
            color: var(--dark);
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        .order-btn.continue:hover {
            background: var(--light-gray);
            transform: translateY(-3px);
            box-shadow: 0 6px 18px rgba(0,0,0,0.12);
        }

        .order-btn.view-order {
            background: var(--dark);
            color: var(--white);
            box-shadow: 0 6px 18px rgba(0,0,0,0.15);
        }

        .order-btn.view-order:hover {
            background: #111;
            transform: translateY(-3px);
            box-shadow: 0 8px 22px rgba(0,0,0,0.2);
        }

        /* 订单错误提示模态框样式 */
        .order-error-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 3000;
            justify-content: center;
            align-items: center;
        }

        .order-error-content {
            background: var(--white);
            border-radius: 16px;
            width: 420px;
            padding: 40px 35px;
            text-align: center;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
            position: relative;
            transform: translateY(-20px);
            opacity: 0;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        .order-error-content.show {
            transform: translateY(0);
            opacity: 1;
        }

        .order-error-icon {
            width: 90px;
            height: 90px;
            border-radius: 50%;
            background: rgba(220, 53, 69, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            box-shadow: 0 6px 15px rgba(220, 53, 69, 0.2);
            position: relative;
            animation: pulse 1.5s infinite;
        }

        .order-error-icon i {
            font-size: 48px;
            color: var(--error);
        }

        .order-error-title {
            font-size: 26px;
            font-weight: 800;
            margin-bottom: 15px;
            color: var(--dark);
            letter-spacing: -0.5px;
        }

        .order-error-text {
            font-size: 17px;
            color: var(--secondary);
            line-height: 1.6;
            margin-bottom: 30px;
            padding: 0 15px;
        }

        .order-error-button {
            display: block;
            width: 100%;
            padding: 16px 0;
            border-radius: 12px;
            font-size: 17px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            background: var(--dark);
            color: var(--white);
            border: none;
            position: relative;
            overflow: hidden;
            box-shadow: 0 6px 18px rgba(0,0,0,0.15);
        }

        .order-error-button:hover {
            background: #111;
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }

        .order-error-button:active {
            transform: translateY(0);
        }

        .order-error-button::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(to right, transparent, rgba(255,255,255,0.2), transparent);
            transform: translateX(-100%);
            transition: transform 0.6s ease;
        }

        .order-error-button:hover::before {
            transform: translateX(100%);
        }

        /* 动画效果 */
        @keyframes pulse {
            0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.4); }
            70% { transform: scale(1); box-shadow: 0 0 0 15px rgba(220, 53, 69, 0); }
            100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); }
        }



        /* 添加评论区域样式 */
        .add-comment-section {
            margin-top: 30px;
            padding: 20px;
            background: var(--light);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }

        .add-comment-section h4 {
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 15px;
            color: var(--dark);
            position: relative;
            padding-bottom: 8px;
        }

        .add-comment-section h4::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 50px;
            height: 3px;
            background: var(--dark);
            border-radius: 2px;
        }

        .comment-input-container {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .comment-input-container textarea {
            width: 100%;
            height: 100px;
            padding: 15px;
            border: 1px solid var(--light-gray);
            border-radius: 10px;
            font-size: 15px;
            resize: vertical;
            transition: var(--transition);
            outline: none;
        }

        .comment-input-container textarea:focus {
            border-color: var(--dark);
            box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.05);
        }


        /* 评论成功提示框样式 */
        .comment-success-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 3000;
            justify-content: center;
            align-items: center;
        }

        .comment-success-content {
            background: var(--white);
            border-radius: 16px;
            width: 380px;
            padding: 35px 30px;
            text-align: center;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
            position: relative;
            transform: translateY(-20px);
            opacity: 0;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        .comment-success-content.show {
            transform: translateY(0);
            opacity: 1;
        }

        .comment-success-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: rgba(40, 167, 69, 0.15);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            box-shadow: 0 6px 15px rgba(40, 167, 69, 0.2);
        }

        .comment-success-icon i {
            font-size: 48px;
            color: var(--success);
        }

        .comment-success-title {
            font-size: 26px;
            font-weight: 800;
            margin-bottom: 15px;
            color: var(--dark);
            letter-spacing: -0.5px;
        }

        .comment-success-text {
            font-size: 17px;
            color: var(--secondary);
            line-height: 1.6;
            margin-bottom: 30px;
            padding: 0 15px;
        }

        .comment-success-button {
            display: block;
            width: 100%;
            padding: 16px 0;
            border-radius: 12px;
            font-size: 17px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            background: var(--dark);
            color: var(--white);
            border: none;
            position: relative;
            overflow: hidden;
            box-shadow: 0 6px 18px rgba(0,0,0,0.15);
        }

        .comment-success-button:hover {
            background: #111;
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<nav class="navbar">
    <div class="logo">
        <i class="fas fa-recycle"></i>
        <h1>二手易购</h1>
    </div>

    <div class="search-container">
        <input type="text" id="searchInput" placeholder="搜索商品...">
        <button id="searchBtn"><i class="fas fa-search"></i></button>
    </div>

    <div class="nav-links">
        <a href="#" class="nav-link" id="myGoodsLink">
            <i class="fas fa-box"></i>
            <span>我的商品</span>
        </a>
        <a href="#" class="nav-link" id="ordersLink">
            <i class="fas fa-file-invoice"></i>
            <span>订单</span>
        </a>
        <a href="#" class="nav-link" id="commentsLink">
            <i class="fas fa-comment-alt"></i>
            <span>评论</span>
        </a>
        <a href="#" class="nav-link" id="cartLink">
            <i class="fas fa-shopping-cart"></i>
            <span>购物车</span>
            <span class="badge" id="cartCount">0</span>
        </a>
    </div>

    <div class="user-menu" id="userMenu">
        <span id="usernameDisplay">游客</span>
        <div class="user-avatar">
            <i class="fas fa-user"></i>
        </div>
        <div class="dropdown-menu" id="dropdownMenu">
            <a href="#" class="dropdown-item" id="profileLink">
                <i class="fas fa-user-circle"></i>个人中心
            </a>
            <div class="divider"></div>
            <a href="#" class="dropdown-item" id="logoutLink">
                <i class="fas fa-sign-out-alt"></i>退出登录
            </a>
        </div>
    </div>
</nav>

<!-- 主内容区域 -->
<div class="container">
    <!-- 分类筛选 -->
    <div class="categories-section">
        <h3 class="categories-title">商品分类</h3>
        <div class="categories" id="categoriesContainer">
            <button class="category-btn active">全部</button>
            <!-- 分类将通过JS动态加载 -->
        </div>
    </div>

    <!-- 商品网格 -->
    <div class="products-grid" id="productsGrid">
        <!-- 商品将通过JS动态加载 -->
    </div>

    <!-- 加载动画 -->
    <div class="loader" id="loader">
        <div class="spinner"></div>
        <p>正在加载商品...</p>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" id="emptyState" style="display: none;">
        <i class="fas fa-box-open"></i>
        <h3>暂无商品</h3>
        <p>当前分类下没有商品，请尝试其他分类</p>
    </div>
</div>

<!-- 商品详情模态框 -->
<div class="modal" id="productModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">商品详情</h3>
            <button class="close-modal" id="closeModal">&times;</button>
        </div>
        <div class="modal-body">
            <div class="product-gallery">
                <div class="main-image">
                    <img id="mainProductImage" src="https://via.placeholder.com/600x400?text=Product+Image" alt="商品主图">
                </div>
                <div class="thumbnails">
                    <!-- 缩略图将通过JS动态加载 -->
                </div>
            </div>

            <div class="product-details">
                <h2 class="product-title" id="productTitle">商品标题</h2>
                <div class="product-meta-info">
                    <div>
                        <i class="fas fa-shopping-cart"></i> 被加入购物车: <span id="productCartCount">0</span> 次
                    </div>
                    <div>
                        <i class="fas fa-comment"></i> 评论: <span id="productCommentsCount">8</span>
                    </div>
                </div>

                <div class="price-section">
                    <div class="price-label">价格</div>
                    <div class="price-value" id="productPrice">¥0.00</div>
                    <div class="stock-info">
                        库存: <span id="productStock">0</span> 件
                    </div>
                </div>

                <!-- 数量选择器 -->
                <div class="quantity-control">
                    <div class="quantity-label">数量:</div>
                    <button class="quantity-btn" id="decreaseQuantity">-</button>
                    <input type="number" class="quantity-input" id="quantityInput" value="1" min="1">
                    <button class="quantity-btn" id="increaseQuantity">+</button>
                </div>
                <div class="stock-warning" id="stockWarning">已达到库存上限</div>

                <div class="action-buttons">
                    <button class="btn btn-dark" id="buyBtn">
                        <i class="fas fa-shopping-bag"></i> 立即购买
                    </button>
                    <button class="btn btn-outline" id="addToCartBtn">
                        <i class="fas fa-cart-plus"></i> 加入购物车
                    </button>
                </div>

                <div class="product-description-full" id="productFullDescription">
                    商品详细描述将在这里显示...
                </div>

                <div class="comments-title">用户评论</div>
                <div class="comments-section" id="commentsSection">
                    <!-- 评论将通过JS动态加载 -->
                </div>
                <div class="no-comments" id="noComments" style="display: none;">
                    <i class="fas fa-comment-slash"></i>
                    <p>该商品暂无评论</p>
                </div>


                <!-- 在商品详情页的评论区添加评论按钮和输入框 -->
                <div class="add-comment-section">
                    <h4>发表评论</h4>
                    <div class="comment-input-container">
                        <textarea id="commentInput" placeholder="请输入您的评论..."></textarea>
                        <button id="submitCommentBtn" class="btn btn-dark">
                            <i class="fas fa-paper-plane"></i> 提交评论
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 浮动发布按钮 -->
<div class="floating-btn" id="publishBtn">
    <i class="fas fa-plus"></i>
</div>

<!-- 购物车成功提示框 -->
<div class="cart-confirm-modal" id="cartConfirmModal">
    <div class="cart-confirm-content">
        <div class="cart-confirm-icon">
            <i class="fas fa-check-circle"></i>
        </div>
        <h3 class="cart-confirm-title">成功添加到购物车</h3>
        <p class="cart-confirm-text">商品已成功加入您的购物车，您想继续购物还是去购物车结算？</p>
        <div class="cart-confirm-buttons">
            <button class="cart-confirm-btn continue" id="continueShoppingBtn">继续购物</button>
            <button class="cart-confirm-btn view-cart" id="viewCartBtn">查看购物车</button>
        </div>
    </div>
</div>

<!-- 购物车失败提示框 -->
<div class="cart-error-modal" id="cartErrorModal">
    <div class="cart-error-content">
        <div class="cart-error-icon">
            <i class="fas fa-exclamation-triangle"></i>
        </div>
        <h3 class="cart-error-title">添加购物车失败</h3>
        <p class="cart-error-text" id="errorMessage">商品库存不足，无法添加到购物车</p>
        <button class="cart-error-button" id="closeErrorBtn">好的，我知道了</button>
    </div>
</div>

<!-- 商品发布模态框 -->
<div class="publish-modal" id="publishModal">
    <div class="publish-content">
        <div class="publish-header">
            <h3 class="publish-title">发布商品</h3>
            <button class="close-publish" id="closePublish">&times;</button>
        </div>
        <div class="publish-body">
            <form id="publishForm">
                <div class="form-group">
                    <label for="goodsName" class="form-label">商品名称</label>
                    <input type="text" id="goodsName" class="form-control" placeholder="输入商品名称" maxlength="50" required>
                    <div class="error-message" id="nameError">请输入商品名称</div>
                </div>

                <div class="form-group">
                    <label for="goodsPrice" class="form-label">商品价格</label>
                    <div class="price-input-container">
                        <span class="price-prefix">¥</span>
                        <input type="number" id="goodsPrice" class="form-control price-input"
                               placeholder="0.00" min="0" step="0.01" required>
                    </div>
                    <div class="error-message" id="priceError">请输入有效的价格</div>
                </div>

                <div class="form-group">
                    <label for="goodsStock" class="form-label">库存数量</label>
                    <input type="number" id="goodsStock" class="form-control"
                           placeholder="输入库存数量" min="1" max="9999" required>
                    <div class="error-message" id="stockError">请输入有效的库存数量</div>
                </div>

                <div class="form-group">
                    <label for="goodsCategory" class="form-label">商品分类</label>
                    <select id="goodsCategory" class="category-select" required>
                        <option value="" disabled selected>选择分类</option>
                        <!-- 分类将通过JS动态加载 -->
                    </select>
                    <div class="error-message" id="categoryError">请选择商品分类</div>
                </div>

                <div class="form-group">
                    <label for="goodsDescription" class="form-label">商品描述</label>
                    <textarea id="goodsDescription" class="form-control"
                              placeholder="输入商品详细描述..." rows="4" maxlength="500" required></textarea>
                    <div class="form-hint">最多500个字符</div>
                    <div class="error-message" id="descriptionError">请输入商品描述</div>
                </div>

                <div class="publish-action">
                    <button type="button" class="btn btn-cancel" id="cancelPublishBtn">
                        <i class="fas fa-times"></i> 取消
                    </button>
                    <button type="submit" class="btn btn-publish" id="submitPublishBtn">
                        <i class="fas fa-check"></i> 发布商品
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 余额确认模态框 -->
<div class="balance-confirm-modal" id="balanceConfirmModal">
    <div class="balance-confirm-content">
        <div class="balance-confirm-header">
            <h3>确认下单</h3>
            <button class="close-balance-modal" id="closeBalanceModal">&times;</button>
        </div>
        <div class="balance-confirm-body">
            <div class="balance-info">
                <p>您当前余额为: <span id="userBalance">¥0.00</span></p>
                <p>实际下单金额: <span id="orderAmount">¥0.00</span></p>
            </div>
            <div class="balance-action">
                <button class="btn btn-cancel" id="cancelOrderBtn">取消</button>
                <button class="btn btn-confirm" id="confirmOrderBtn">确认下单</button>
            </div>
        </div>
    </div>
</div>

<!-- 订单成功确认模态框 -->
<div class="order-confirm-modal" id="orderConfirmModal">
    <div class="order-confirm-content">
        <div class="order-confirm-header">
            <h3 class="order-confirm-title">订单创建成功</h3>
            <button class="close-confirm" id="closeConfirm">&times;</button>
        </div>
        <div class="order-details">
            <div class="order-detail-row">
                <span class="order-detail-label">商品名称:</span>
                <span class="order-detail-value" id="confirmProductName"></span>
            </div>
            <div class="order-detail-row">
                <span class="order-detail-label">数量:</span>
                <span class="order-detail-value" id="confirmQuantity"></span>
            </div>
            <div class="order-detail-row">
                <span class="order-detail-label">单价:</span>
                <span class="order-detail-value" id="confirmUnitPrice"></span>
            </div>
            <div class="order-detail-row">
                <span class="order-detail-label">总价:</span>
                <span class="order-detail-value total-price" id="confirmTotalPrice"></span>
            </div>
        </div>
        <div class="order-actions">
            <button class="order-btn continue" id="orderContinueBtn">
                <i class="fas fa-shopping-bag"></i> 继续购物
            </button>
            <button class="order-btn view-order" id="viewOrderBtn">
                <i class="fas fa-file-invoice"></i> 查看订单
            </button>
        </div>
    </div>
</div>

<!-- 订单错误提示模态框 -->
<div class="order-error-modal" id="orderErrorModal">
    <div class="order-error-content" id="orderErrorContent">
        <div class="order-error-icon">
            <i class="fas fa-exclamation-triangle"></i>
        </div>
        <h3 class="order-error-title">下单失败</h3>
        <p class="order-error-text" id="orderErrorMessage">商品库存不足，无法完成下单</p>
        <button class="order-error-button" id="closeOrderErrorBtn">好的，我知道了</button>
    </div>
</div>

<div class="comment-success-modal" id="commentSuccessModal">
    <div class="comment-success-content">
        <div class="comment-success-icon">
            <i class="fas fa-check-circle"></i>
        </div>
        <h3 class="comment-success-title">评论发布成功</h3>
        <p class="comment-success-text">您的评论已成功发布！</p>
        <button class="comment-success-button" id="closeCommentSuccessBtn">好的</button>
    </div>
</div>

<script>
    // 用户信息（从localStorage中获取）
    let userInfo = JSON.parse(localStorage.getItem('userInfo')) || null;
    let currentProductId = null;
    let currentCategory = 'all';
    let currentSearch = '';
    let cartItems = JSON.parse(localStorage.getItem('cartItems')) || [];
    let currentProduct = null;

    // DOM元素
    const productsGrid = document.getElementById('productsGrid');
    const categoriesContainer = document.getElementById('categoriesContainer');
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const loader = document.getElementById('loader');
    const emptyState = document.getElementById('emptyState');
    const productModal = document.getElementById('productModal');
    const closeModal = document.getElementById('closeModal');
    const productTitle = document.getElementById('productTitle');
    const productPrice = document.getElementById('productPrice');
    const productStock = document.getElementById('productStock');
    const productFullDescription = document.getElementById('productFullDescription');
    const commentsSection = document.getElementById('commentsSection');
    const noComments = document.getElementById('noComments');
    const buyBtn = document.getElementById('buyBtn');
    const addToCartBtn = document.getElementById('addToCartBtn');
    const usernameDisplay = document.getElementById('usernameDisplay');
    const userMenu = document.getElementById('userMenu');
    const dropdownMenu = document.getElementById('dropdownMenu');
    const cartCount = document.getElementById('cartCount');
    const publishBtn = document.getElementById('publishBtn');
    const notification = document.getElementById('notification');
    const mainProductImage = document.getElementById('mainProductImage');
    const thumbnails = document.querySelector('.thumbnails');
    const productCartCount = document.getElementById('productCartCount');
    const productCommentsCount = document.getElementById('productCommentsCount');
    const decreaseQuantity = document.getElementById('decreaseQuantity');
    const increaseQuantity = document.getElementById('increaseQuantity');
    const quantityInput = document.getElementById('quantityInput');
    const stockWarning = document.getElementById('stockWarning');
    const cartConfirmModal = document.getElementById('cartConfirmModal');
    const continueShoppingBtn = document.getElementById('continueShoppingBtn');
    const viewCartBtn = document.getElementById('viewCartBtn');
    const cartErrorModal = document.getElementById('cartErrorModal');
    const errorMessage = document.getElementById('errorMessage');
    const closeErrorBtn = document.getElementById('closeErrorBtn');
    const publishModal = document.getElementById('publishModal');
    const closePublish = document.getElementById('closePublish');
    const cancelPublishBtn = document.getElementById('cancelPublishBtn');
    const submitPublishBtn = document.getElementById('submitPublishBtn');
    const publishForm = document.getElementById('publishForm');
    const goodsName = document.getElementById('goodsName');
    const goodsPrice = document.getElementById('goodsPrice');
    const goodsStock = document.getElementById('goodsStock');
    const goodsCategory = document.getElementById('goodsCategory');
    const goodsDescription = document.getElementById('goodsDescription');

    // 当前商品库存量
    let currentStock = 0;

    // API 基础URL
    const API_BASE_URL = 'http://localhost:8080';

    // 初始化页面
    document.addEventListener('DOMContentLoaded', function() {
        // 更新用户信息显示
        updateUserInfo();

        // 更新购物车数量
        updateCartCount(cartItems.length);

        // 获取购物车数量
        fetchCartCount();

        // 获取商品数据
        fetchProducts();

        // 获取商品分类
        fetchCategories();

        // 设置事件监听器
        setupEventListeners();
    });



    // 更新用户信息显示
    function updateUserInfo() {
        if (userInfo) {
            usernameDisplay.textContent = userInfo.username || '游客';
        } else {
            // 如果用户未登录，跳转到登录页
            window.location.href = 'login.html';
        }
    }

    // 显示通知
    function showNotification(message, isError = false) {
        notification.textContent = message;
        notification.className = 'notification';

        if (isError) {
            notification.classList.add('error');
        }

        // 显示通知
        notification.style.display = 'block';

        setTimeout(() => {
            notification.style.display = 'none';
        }, 3000);
    }

    // 显示购物车成功提示框
    function showCartConfirmModal() {
        cartConfirmModal.style.display = 'flex';
    }

    // 隐藏购物车成功提示框
    function hideCartConfirmModal() {
        cartConfirmModal.style.display = 'none';
    }

    // 显示购物车失败提示框
    function showCartErrorModal(message) {
        errorMessage.textContent = message;
        cartErrorModal.style.display = 'flex';
    }

    // 隐藏购物车失败提示框
    function hideCartErrorModal() {
        cartErrorModal.style.display = 'none';
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 搜索功能
        searchBtn.addEventListener('click', handleSearch);
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                handleSearch();
            }
        });

        // 分类按钮点击事件
        document.querySelectorAll('.category-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                // 移除所有按钮的active类
                document.querySelectorAll('.category-btn').forEach(b => {
                    b.classList.remove('active');
                });

                // 给当前按钮添加active类
                this.classList.add('active');

                // 更新当前分类
                currentCategory = this.textContent === '全部' ? 'all' : this.textContent;

                // 重新获取商品
                fetchProducts();
            });
        });

        // 模态框关闭
        closeModal.addEventListener('click', function() {
            productModal.style.display = 'none';
        });

        // 点击模态框外部关闭
        window.addEventListener('click', function(event) {
            if (event.target === productModal) {
                productModal.style.display = 'none';
            }
            if (event.target === cartConfirmModal) {
                hideCartConfirmModal();
            }
            if (event.target === cartErrorModal) {
                hideCartErrorModal();
            }
            if (event.target === publishModal) {
                publishModal.style.display = 'none';
            }
        });

        // 用户菜单
        userMenu.addEventListener('click', function() {
            dropdownMenu.classList.toggle('show');
        });

        // 关闭用户菜单（点击页面其他地方）
        window.addEventListener('click', function(e) {
            if (!userMenu.contains(e.target)) {
                dropdownMenu.classList.remove('show');
            }
        });

        // 添加点击模态框外部关闭功能
        window.addEventListener('click', function(event) {
            if (event.target === document.getElementById('balanceConfirmModal')) {
                document.getElementById('balanceConfirmModal').style.display = 'none';
            }
        });

        // 购买按钮
        buyBtn.addEventListener('click', async function() {
            if (!userInfo) {
                showNotification('请先登录', true);
                return;
            }

            // 获取数量
            const quantity = parseInt(quantityInput.value);

            // 计算总价
            const price = parseFloat(productPrice.textContent.replace('¥', ''));
            const totalPrice = price * quantity;

            try {
                // 获取当前用户余额
                const response = await fetch(`${API_BASE_URL}/user/info/${userInfo.userId}`);
                if (!response.ok) {
                    throw new Error('获取用户信息失败');
                }
                const userData = await response.json();

                // 显示余额确认模态框
                document.getElementById('userBalance').textContent = `¥${userData.uBalance.toFixed(2)}`;
                document.getElementById('orderAmount').textContent = `¥${totalPrice.toFixed(2)}`;
                document.getElementById('balanceConfirmModal').style.display = 'flex';
            } catch (error) {
                console.error('获取用户信息失败:', error);
                showNotification('获取用户信息失败', true);
            }
        });


        // 加入购物车按钮
        addToCartBtn.addEventListener('click', function() {
            if (!userInfo) {
                showNotification('请先登录', true);
                return;
            }

            // 获取数量
            const quantity = parseInt(quantityInput.value);

            // 添加到购物车
            addToCart(currentProductId, quantity);
        });

        // 退出登录
        document.getElementById('logoutLink').addEventListener('click', function(e) {
            e.preventDefault();
            localStorage.removeItem('userInfo');
            window.location.href = 'login.html';
        });

        // 发布按钮
        publishBtn.addEventListener('click', function() {
            // 显示发布商品模态框
            publishModal.style.display = 'block';
            // 重置表单
            publishForm.reset();
            // 隐藏所有错误消息
            document.querySelectorAll('.error-message').forEach(el => {
                el.style.display = 'none';
            });
        });

        // 我的商品
        document.getElementById('myGoodsLink').addEventListener('click', function(e) {
            e.preventDefault();
            window.location.href = 'my-goods.html';
        });

        // 订单
        document.getElementById('ordersLink').addEventListener('click', function(e) {
            e.preventDefault();
            window.location.href = 'orders.html';
        });

        // 评论
        document.getElementById('commentsLink').addEventListener('click', function(e) {
            e.preventDefault();
            window.location.href = 'my-comments.html';
        });

        // 购物车
        document.getElementById('cartLink').addEventListener('click', function(e) {
            e.preventDefault();
            window.location.href = 'cart.html';
        });

        // 个人资料
        document.getElementById('profileLink').addEventListener('click', function(e) {
            e.preventDefault();
            window.location.href = 'profile.html';
        });

        // 数量控制按钮
        decreaseQuantity.addEventListener('click', function() {
            const current = parseInt(quantityInput.value);
            if (current > 1) {
                quantityInput.value = current - 1;
                updateQuantityControls();
            }
        });

        increaseQuantity.addEventListener('click', function() {
            const current = parseInt(quantityInput.value);
            if (current < currentStock) {
                quantityInput.value = current + 1;
                updateQuantityControls();
            }
        });

        quantityInput.addEventListener('change', function() {
            let value = parseInt(this.value);
            if (isNaN(value) || value < 1) {
                value = 1;
            } else if (value > currentStock) {
                value = currentStock;
                showNotification('数量不能超过库存', true);
            }
            this.value = value;
            updateQuantityControls();
        });

        // 购物车成功提示框按钮
        continueShoppingBtn.addEventListener('click', function() {
            hideCartConfirmModal();
        });

        viewCartBtn.addEventListener('click', function() {
            hideCartConfirmModal();
            // 跳转到购物车页面
            window.location.href = 'cart.html';
        });

        // 购物车失败提示框按钮
        closeErrorBtn.addEventListener('click', function() {
            hideCartErrorModal();
        });

        // 发布商品模态框关闭按钮
        closePublish.addEventListener('click', function() {
            publishModal.style.display = 'none';
        });

        // 发布商品取消按钮
        cancelPublishBtn.addEventListener('click', function() {
            publishModal.style.display = 'none';
        });

        // 表单提交事件
        publishForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handlePublishGoods();
        });

        // 余额确认模态框关闭按钮
        document.getElementById('closeBalanceModal').addEventListener('click', function() {
            document.getElementById('balanceConfirmModal').style.display = 'none';
        });

        // 余额确认模态框取消按钮
        document.getElementById('cancelOrderBtn').addEventListener('click', function() {
            document.getElementById('balanceConfirmModal').style.display = 'none';
        });

        // 余额确认模态框确认按钮
        document.getElementById('confirmOrderBtn').addEventListener('click', function() {
            const quantity = parseInt(quantityInput.value);
            const price = parseFloat(productPrice.textContent.replace('¥', ''));
            const totalPrice = price * quantity;

            // 获取用户余额（从余额确认模态框中显示的用户余额）
            const balanceText = document.getElementById('userBalance').textContent;
            const userBalance = parseFloat(balanceText.replace('¥', ''));

            if (userBalance >= totalPrice) {
                // 余额足够，创建订单
                createOrder(currentProductId, quantity);
                document.getElementById('balanceConfirmModal').style.display = 'none';
            } else {
                // 余额不足时显示订单错误模态框
                showOrderError('余额不足，请充值');
            }
        });

        // 订单成功模态框按钮
        closeConfirm.addEventListener('click', function() {
            orderConfirmModal.style.display = 'none';
        });

        continueShoppingBtn.addEventListener('click', function() {
            orderConfirmModal.style.display = 'none';
            productModal.style.display = 'none';
        });

        viewOrderBtn.addEventListener('click', function() {
            orderConfirmModal.style.display = 'none';
            productModal.style.display = 'none';
            window.location.href = 'orders.html';
        });

        // 订单错误模态框按钮
        closeOrderErrorBtn.addEventListener('click', function() {
            orderErrorModal.style.display = 'none';
        });

        document.getElementById('orderContinueBtn').addEventListener('click', function() {
            orderConfirmModal.style.display = 'none';
            productModal.style.display = 'none';
        });

        document.getElementById('viewOrderBtn').addEventListener('click', function() {
            orderConfirmModal.style.display = 'none';
            productModal.style.display = 'none';
            window.location.href = 'orders.html';
        });

        document.getElementById('closeOrderErrorBtn').addEventListener('click', function() {
            hideOrderErrorModal();
        });


        // 点击模态框外部关闭
        window.addEventListener('click', function(event) {
            if (event.target === orderErrorModal) {
                hideOrderErrorModal();
            }
        });

        // 评论成功提示框关闭按钮
        document.getElementById('closeCommentSuccessBtn').addEventListener('click', hideCommentSuccess);

        // 点击模态框外部关闭
        window.addEventListener('click', function(event) {
            if (event.target === document.getElementById('commentSuccessModal')) {
                hideCommentSuccess();
            }
        });

        // 表单输入验证
        goodsName.addEventListener('blur', validateName);
        goodsPrice.addEventListener('blur', validatePrice);
        goodsStock.addEventListener('blur', validateStock);
        goodsCategory.addEventListener('blur', validateCategory);
        goodsDescription.addEventListener('blur', validateDescription);
    }

    // 更新数量控制按钮状态
    function updateQuantityControls() {
        const current = parseInt(quantityInput.value);

        // 更新减少按钮状态
        decreaseQuantity.disabled = current <= 1;

        // 更新增加按钮状态
        increaseQuantity.disabled = current >= currentStock;

        // 显示/隐藏库存警告
        stockWarning.classList.toggle('show', current >= currentStock);
    }

    // 处理搜索
    function handleSearch() {
        currentSearch = searchInput.value.trim();
        fetchProducts();
    }

    // 获取商品分类
    function fetchCategories() {
        fetch(`${API_BASE_URL}/Goods/categories`)
            .then(response => response.json())
            .then(categories => {
                // 添加分类按钮
                categories.forEach(category => {
                    if (category) {
                        const button = document.createElement('button');
                        button.className = 'category-btn';
                        button.textContent = category;

                        button.addEventListener('click', function() {
                            document.querySelectorAll('.category-btn').forEach(b => {
                                b.classList.remove('active');
                            });
                            this.classList.add('active');
                            currentCategory = category;
                            fetchProducts();
                        });

                        categoriesContainer.appendChild(button);
                    }
                });

                // 添加分类到发布表单
                categories.forEach(category => {
                    if (category) {
                        const option = document.createElement('option');
                        option.value = category;
                        option.textContent = category;
                        goodsCategory.appendChild(option);
                    }
                });
            })
            .catch(error => {
                console.error('获取分类失败:', error);
                showNotification('获取分类失败', true);
            });
    }

    // 获取商品数据
    function fetchProducts() {
        loader.style.display = 'block';
        productsGrid.innerHTML = '';
        emptyState.style.display = 'none';

        let url;
        if (currentCategory === 'all' && currentSearch === '') {
            url = `${API_BASE_URL}/Goods/all`;
        } else if (currentCategory !== 'all') {
            url = `${API_BASE_URL}/Goods/category/${encodeURIComponent(currentCategory)}`;
        } else {
            url = `${API_BASE_URL}/Goods/search?keyword=${encodeURIComponent(currentSearch)}`;
        }

        fetch(url)
            .then(response => response.json())
            .then(products => {
                // 显示商品
                if (products.length > 0) {
                    renderProducts(products);
                    productsGrid.style.display = 'grid';
                    emptyState.style.display = 'none';
                } else {
                    productsGrid.style.display = 'none';
                    emptyState.style.display = 'block';
                }

                loader.style.display = 'none';
            })
            .catch(error => {
                console.error('获取商品失败:', error);
                showNotification('获取商品失败', true);
                loader.style.display = 'none';
                emptyState.style.display = 'block';
            });
    }

    // 渲染商品
    function renderProducts(productsList) {
        productsGrid.innerHTML = '';

        productsList.forEach(product => {
            const card = document.createElement('div');
            card.className = 'product-card';
            card.innerHTML = `
                <div class="product-image">
                    <img src="${product.gImage || 'https://via.placeholder.com/300x300?text=No+Image'}" alt="${product.gName}">
                </div>
                <div class="product-info">
                    <h3 class="product-name">${product.gName}</h3>
                    <p class="product-description">${product.gDescription || '暂无描述'}</p>
                    <div class="product-price">¥${product.gPrice.toFixed(2)}</div>
                    <div class="product-meta">
                        <span>${product.gCategory || '未分类'}</span>
                        <span>库存: ${product.gStockQuantity}</span>
                    </div>
                </div>
            `;

            card.addEventListener('click', () => {
                openProductModal(product);
            });

            productsGrid.appendChild(card);
        });
    }

    // 打开商品模态框
    function openProductModal(product) {
        currentProduct = product; // 保存当前商品对象

        currentProductId = product.gId;
        currentStock = product.gStockQuantity;

        // 设置商品信息
        productTitle.textContent = product.gName;
        productPrice.textContent = `¥${product.gPrice.toFixed(2)}`;
        productStock.textContent = currentStock;
        productFullDescription.textContent = product.gDescription || '暂无详细描述';

        // 重置数量选择器
        quantityInput.value = 1;
        updateQuantityControls();
        stockWarning.classList.remove('show');

        // 设置图片
        mainProductImage.src = product.gImage || 'https://via.placeholder.com/600x400?text=No+Image';

        // 清空缩略图
        thumbnails.innerHTML = '';

        // 添加缩略图（这里简化为一张图片）
        if (product.gImage) {
            const thumbnail = document.createElement('div');
            thumbnail.className = 'thumbnail';
            thumbnail.innerHTML = `<img src="${product.gImage}" alt="缩略图">`;
            thumbnail.addEventListener('click', () => {
                mainProductImage.src = product.gImage;
            });
            thumbnails.appendChild(thumbnail);
        }

        // 获取购物车次数
        fetch(`${API_BASE_URL}/Goods/cart-count/${product.gId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP 错误! 状态: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 确保我们访问的是正确的属性
                const count = typeof data === 'number' ? data : data.count;
                console.log('获取购物车次数成功:', count);
                productCartCount.textContent = count;
            })
            .catch(error => {
                console.error('获取购物车次数失败:', error);
                productCartCount.textContent = '0';
            });

        // 加载评论
        loadComments(product.gId);

        // 显示模态框
        productModal.style.display = 'block';
    }

    // 显示评论成功提示框
    function showCommentSuccess() {
        const commentSuccessContent = document.getElementById('commentSuccessModal').querySelector('.comment-success-content');
        commentSuccessContent.classList.add('show');
        document.getElementById('commentSuccessModal').style.display = 'flex';
    }

    // 隐藏评论成功提示框
    function hideCommentSuccess() {
        const commentSuccessContent = document.getElementById('commentSuccessModal').querySelector('.comment-success-content');
        commentSuccessContent.classList.remove('show');
        setTimeout(() => {
            document.getElementById('commentSuccessModal').style.display = 'none';
        }, 300);
    }

    // 提交评论功能
    document.getElementById('submitCommentBtn').addEventListener('click', function() {
        const commentText = document.getElementById('commentInput').value.trim();
        const productId = currentProductId;

        if (!userInfo) {
            showNotification('请先登录', true);
            return;
        }

        if (!commentText) {
            showNotification('评论内容不能为空', true);
            return;
        }

        // 显示加载状态
        this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
        this.disabled = true;

        // 调用后端API提交评论
        submitComment(productId, commentText);
    });

    // 修改submitComment函数
    async function submitComment(productId, commentText) {
        const submitBtn = document.getElementById('submitCommentBtn');
        try {
            // 显示加载状态
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
            submitBtn.disabled = true;

            const response = await fetch(`${API_BASE_URL}/comments/add`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    cUserId: userInfo.userId,
                    cGoodsId: productId,
                    cBio: commentText
                })
            });

            const result = await response.json();

            if (response.ok && result) {
                // 显示评论成功提示
                showCommentSuccess();

                // 清空输入框
                document.getElementById('commentInput').value = '';
                // 重新加载评论
                loadComments(productId);
            } else {
                throw new Error(result.message || '评论提交失败');
            }
        } catch (error) {
            console.error('提交评论失败:', error);
            showNotification('提交评论失败: ' + error.message, true);
        } finally {
            // 恢复按钮状态
            submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> 提交评论';
            submitBtn.disabled = false;
        }
    }


    // 加载评论
    function loadComments(productId) {
        fetch(`${API_BASE_URL}/comments/goods/${productId}`)
            .then(response => response.json())
            .then(comments => {
                if (comments.length > 0) {
                    commentsSection.innerHTML = '';
                    noComments.style.display = 'none';
                    productCommentsCount.textContent = comments.length;

                    comments.forEach(comment => {
                        const commentEl = document.createElement('div');
                        commentEl.className = 'comment';

                        // 使用返回的用户名，如果为空则显示"匿名用户"
                        const displayName = comment.userName || '匿名用户';

                        commentEl.innerHTML = `
                        <div class="comment-header">
                            <div class="comment-avatar">
                                <img src="https://api.dicebear.com/7.x/bottts/svg?seed=${displayName}" alt="用户头像">
                            </div>
                            <div>
                                <div class="comment-user">${displayName}</div>
                            </div>
                        </div>
                        <div class="comment-text">
                            ${comment.cBio}
                        </div>
                    `;
                        commentsSection.appendChild(commentEl);
                    });
                } else {
                    commentsSection.innerHTML = '';
                    noComments.style.display = 'block';
                    productCommentsCount.textContent = '0';
                }
            })
            .catch(error => {
                console.error('获取评论失败:', error);
                commentsSection.innerHTML = '';
                noComments.style.display = 'block';
                productCommentsCount.textContent = '0';
            });
    }

    // 更新购物车数量
    function updateCartCount(count) {
        cartCount.textContent = count;
    }

    // 添加到购物车
    function addToCart(goodsId, quantity) {
        // 显示加载状态
        addToCartBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        addToCartBtn.disabled = true;

        // 准备请求数据
        const requestData = {
            userId: userInfo.userId,
            goodsId: goodsId,
            quantity: quantity
        };

        // 调用后端API
        fetch(`${API_BASE_URL}/Goods/add-to-cart`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(requestData)
        })
            .then(async response => {
                const data = await response.json(); // 统一获取JSON数据

                if (!response.ok) {
                    // HTTP错误（4xx/5xx）
                    const error = data.error || `HTTP错误! 状态码: ${response.status}`;
                    throw new Error(error);
                }

                // 业务逻辑错误（后端返回200但包含错误信息）
                if (data.error ||
                    data.message.includes("不能超过库存") ||
                    data.message.includes("不存在")) {
                    throw new Error(data.error || data.message);
                }

                // 真正成功的请求
                fetchCartCount();
                showCartConfirmModal();
            })
            .catch(error => {
                console.error('添加到购物车失败:', error);
                showCartErrorModal('添加到购物车失败: ' + error.message);
            })
            .finally(() => {
                addToCartBtn.innerHTML = '<i class="fas fa-cart-plus"></i> 加入购物车';
                addToCartBtn.disabled = false;
            });
    }

    // 获取购物车商品总数（从后端）
    function fetchCartCount() {
        if (!userInfo || !userInfo.userId) return;

        fetch(`${API_BASE_URL}/shoppingCart/total-items/${userInfo.userId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(count => {
                updateCartCount(count);
            })
            .catch(error => {
                console.error('获取购物车数量失败:', error);
                // 失败时显示0
                updateCartCount(0);
            });
    }

    // 在购物车页面执行删除操作后也需要刷新
    // 例如在 cart.html 中删除商品后调用：
    function refreshCartCount() {
        fetchCartCount();
    }

    // 创建订单
    // 点击购买
    function createOrder(goodsId, quantity) {
        // 显示加载状态
        buyBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 下单中...';
        buyBtn.disabled = true;

        // 调用后端创建订单API
        fetch(`${API_BASE_URL}/Goods/create-order?userId=${userInfo.userId}&goodsId=${goodsId}&quantity=${quantity}`, {
            method: 'POST'
        })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => { throw new Error(text) });
                }
                return response.text();
            })
            .then(message => {
                // 显示订单成功模态框
                showOrderSuccess(message);

                // +++ 重新加载商品数据 +++
                // 1. 刷新整个商品列表
                fetchProducts();

                // 2. 如果当前商品详情模态框是打开的，重新加载该商品详情
                if (currentProductId) {
                    fetchProductDetail(currentProductId);
                }
            })
            .catch(error => {
                console.error('下单失败:', error);
                // 显示订单错误模态框
                showOrderError('下单失败: ' + error.message);
            })
            .finally(() => {
                buyBtn.innerHTML = '<i class="fas fa-shopping-bag"></i> 立即购买';
                buyBtn.disabled = false;
            });
    }

    // +++ 获取单个商品详情 +++
    function fetchProductDetail(productId) {
        fetch(`${API_BASE_URL}/Goods/${productId}`)
            .then(response => response.json())
            .then(product => {
                // 更新商品详情模态框中的库存信息
                updateProductModal(product);
            })
            .catch(error => {
                console.error('获取商品详情失败:', error);
            });
    }

    // +++ 更新商品详情模态框 +++
    function updateProductModal(product) {
        // 更新库存显示
        currentStock = product.gStockQuantity;
        productStock.textContent = currentStock;

        // 更新数量选择器
        const currentQuantity = parseInt(quantityInput.value);
        // 如果当前选择的数量大于新的库存，则调整为库存数量
        if (currentQuantity > currentStock) {
            quantityInput.value = currentStock;
        }
        updateQuantityControls();
    }

    // 显示订单成功模态框
    // 显示订单成功模态框
    function showOrderSuccess(message) {
        // 获取订单信息展示元素
        const confirmProductName = document.getElementById('confirmProductName');
        const confirmQuantity = document.getElementById('confirmQuantity');
        const confirmUnitPrice = document.getElementById('confirmUnitPrice');
        const confirmTotalPrice = document.getElementById('confirmTotalPrice');

        // 确保当前商品对象存在
        if (!currentProduct) {
            console.error('currentProduct is not defined');
            showNotification('显示订单信息失败', true);
            return;
        }

        // 填充订单信息
        confirmProductName.textContent = currentProduct.gName;
        confirmQuantity.textContent = quantityInput.value;
        confirmUnitPrice.textContent = `¥${currentProduct.gPrice.toFixed(2)}`;

        const totalPrice = currentProduct.gPrice * parseInt(quantityInput.value);
        confirmTotalPrice.textContent = `¥${totalPrice.toFixed(2)}`;

        // 显示模态框
        orderConfirmModal.style.display = 'flex';
    }

    // 显示订单错误模态框
    function showOrderError(message) {
        const orderErrorContent = document.getElementById('orderErrorContent');
        const orderErrorMessage = document.getElementById('orderErrorMessage');

        orderErrorMessage.textContent = message;
        orderErrorModal.style.display = 'flex';

        // 添加动画效果
        setTimeout(() => {
            orderErrorContent.classList.add('show');
        }, 50);
    }

    // 新增：表单验证函数
    function validateName() {
        const nameError = document.getElementById('nameError');
        if (!goodsName.value.trim()) {
            nameError.style.display = 'block';
            return false;
        }
        nameError.style.display = 'none';
        return true;
    }

    function validatePrice() {
        const priceError = document.getElementById('priceError');
        const price = parseFloat(goodsPrice.value);
        if (isNaN(price) || price <= 0) {
            priceError.style.display = 'block';
            return false;
        }
        priceError.style.display = 'none';
        return true;
    }

    function validateStock() {
        const stockError = document.getElementById('stockError');
        const stock = parseInt(goodsStock.value);
        if (isNaN(stock) || stock < 1 || stock > 9999) {
            stockError.style.display = 'block';
            return false;
        }
        stockError.style.display = 'none';
        return true;
    }

    function validateCategory() {
        const categoryError = document.getElementById('categoryError');
        if (!goodsCategory.value) {
            categoryError.style.display = 'block';
            return false;
        }
        categoryError.style.display = 'none';
        return true;
    }

    function validateDescription() {
        const descriptionError = document.getElementById('descriptionError');
        if (!goodsDescription.value.trim()) {
            descriptionError.style.display = 'block';
            return false;
        }
        descriptionError.style.display = 'none';
        return true;
    }

    // 新增：处理商品发布
    function handlePublishGoods() {
        // 验证所有字段
        const isValid = validateName() & validatePrice() & validateStock() &
            validateCategory() & validateDescription();

        if (!isValid) {
            showNotification('请正确填写所有字段', true);
            return;
        }

        // 准备商品数据
        const goodsData = {
            gName: goodsName.value.trim(),
            gPrice: parseFloat(goodsPrice.value),
            gStockQuantity: parseInt(goodsStock.value),
            gCategory: goodsCategory.value,
            gDescription: goodsDescription.value.trim(),
            gUserId: userInfo.userId,
            gIsActive: true,
            gIsTrade: false
        };

        // 显示加载状态
        submitPublishBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 发布中...';
        submitPublishBtn.disabled = true;

        // 调用后端API创建商品
        fetch(`${API_BASE_URL}/Goods/create`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(goodsData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('创建商品失败: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data && data.gId) {
                    showNotification('商品发布成功!');
                    // 关闭模态框
                    publishModal.style.display = 'none';
                    // 刷新商品列表
                    fetchProducts();
                } else {
                    throw new Error('创建商品失败');
                }
            })
            .catch(error => {
                console.error('发布商品失败:', error);
                showNotification('发布商品失败: ' + error.message, true);
            })
            .finally(() => {
                submitPublishBtn.innerHTML = '<i class="fas fa-check"></i> 发布商品';
                submitPublishBtn.disabled = false;
            });
    }

    // 隐藏订单错误提示模态框
    function hideOrderErrorModal() {
        const orderErrorContent = document.getElementById('orderErrorContent');
        orderErrorContent.classList.remove('show');

        setTimeout(() => {
            orderErrorModal.style.display = 'none';
        }, 300);
    }
</script>
</body>
</html>